package com.android.manghe.search.presenter

import com.android.base.frame.presenter.XPresenter
import com.android.base.okhttp.okUtil.OKHttpUtil
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.model.BaseBack
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.market.model.MarketAuctionRes
import com.android.manghe.mine.model.FansRes
import com.android.manghe.search.activity.SearchBigMarketActivity
import okhttp3.Call
import java.util.*

class PBigMarketSearch : XPresenter<SearchBigMarketActivity>(){

    var mPriceSort = 0 //0无排序 1升序 2降序
    var mFilterType = 0 // 0综合 1销量 2折扣 3价格
    private var mCurrentPage = 1
    private val PageSize = "10"
    private val mAuctionList = ArrayList<FansRes.DataBean.ListBean>()

    private var text = ""

    fun search(isRefresh :Boolean, text: String){
        try{
            if(text.isNotEmpty()){
                this.text = text
            }

            if (isRefresh) {
                mCurrentPage = 1
                mAuctionList.clear()
            }
            val data = HashMap<String, String>()
            data["page"] = mCurrentPage.toString() + ""
            data["size"] = PageSize
            data["q"] = this.text

            if (mPriceSort != 0) {
                data["order"] = "price"
                data["sort"] = if (mPriceSort == 1) "asc" else "desc"
            } else if (mFilterType != 0) {
                //除了 综合 。销量或折扣
                data["order"] = if (mFilterType == 1) "sales" else "discount"
            }

            val headMap = HashMap<String, String>()
            headMap["UID"] = UserHolder.getUID(v)
            headMap["TOKEN"] = UserHolder.getUserInfo(v)!!.TOKEN
            OKHttpUtil(v).urlByHeadData(
                ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_GOODSLISTSDATA,
                data,
                headMap
            )
                .get()
                .execute(object : BaseBack<MarketAuctionRes>() {

                    override fun onSuccess(call: Call, res: MarketAuctionRes?) {
                        if (res != null) {
                            if(res.code == 0){
                                if(res.list.isNullOrEmpty()){
                                    v.noData()
                                }else{
                                    v.update(res.list)
                                }
                            }else{
                                v.searchFail(res.msg)
                            }
                        }else{
                            v.searchFail(null)
                        }
                    }

                    override fun onFailure(e: Exception) {
                        super.onFailure(e)
                        v.searchFail(null)
                    }

                    override fun onComplete() {
                    }
                })
        }catch (e: Exception){
            e.printStackTrace()
        }
    }
}